﻿
package extremefx.geom {
	import flash.geom.Rectangle;	
	
	/**
	 * @author Marcelo Volmaro
	 */
	public final class SizeFit {
		public static function fitTo(pSize:SizeF, pMaxSize:SizeF, pCrop:Boolean = false):Rectangle {
			var xPos:Number, cx:Number, yPos:Number, cy:Number;
			xPos = yPos = cx = cy = 0;

			var mw:Number = pMaxSize.width;
			var mh:Number = pMaxSize.height;
			var cw:Number = pSize.width;
			var ch:Number = pSize.height;
			
			var widthScale:Number = cw / mw;
			var heightScale:Number = ch / mh;

			if (pCrop) {
				var minScale:Number = Math.min(widthScale, heightScale);
				
				if (widthScale < heightScale) {
					ch = mh * minScale;
					cy = (mh - ch) / 2;

				} else {
					cw = mw * minScale;
					cx = (mw - cw) / 2;
				}

				return new Rectangle(cx, cy, cw, ch);
			}
			
			var maxScale:Number = Math.max(widthScale, heightScale);
			
			if (widthScale < heightScale) {
				mw /= maxScale;
				xPos = (pMaxSize.width - mw) / 2;

			} else {
				mh /= maxScale;
				yPos = (pMaxSize.height - mh) / 2;
			}

			return new Rectangle(xPos, yPos, mw, mh);
		}
	}
}
